package com.lagou.framework.context;

import com.lagou.framework.factory.DemoServletContextInitializer;
import com.lagou.framework.factory.DemoWebServerFactory;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;

/**
 * @author mawenjie
 */
public class DemoServletWebServerApplicationContext extends AnnotationConfigWebApplicationContext {

    @Override
    protected void onRefresh() {
        super.onRefresh();
        // 创建并启动WebServer
        try {
            getWebServerFactory().createWebServer(getContextInitializer());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取WebServer工厂
     *
     * @return
     */
    private DemoWebServerFactory getWebServerFactory() {
        String[] beanNames = getBeanFactory().getBeanNamesForType(DemoWebServerFactory.class);
        return getBeanFactory().getBean(beanNames[0], DemoWebServerFactory.class);
    }

    private DemoServletContextInitializer getContextInitializer() {
        return this::initServletContext;
    }

    private void initServletContext(ServletContext servletContext) {
        // 注册 DispatcherServlet 到 ServletContext
        DispatcherServlet dispatcherServlet = (DispatcherServlet) getBean("dispatcherServlet");
        ServletRegistration.Dynamic registration = servletContext.addServlet("dispatcherServlet", dispatcherServlet);
        registration.setLoadOnStartup(1);
        registration.addMapping("/");
    }

}
